package com.mindtree.vi.presentation.servlet;

import java.util.ArrayList;
import java.util.List;

import com.mindtree.vi.business.questionsubmission.QuestionManager;
import com.mindtree.vi.dbaccess.datatypes.problem.Problem;
import com.mindtree.vi.dbaccess.datatypes.problem.ProblemDesc;
import com.mindtree.vi.presentation.annotation.ReferencedBy;
import com.mindtree.vi.presentation.annotation.RequestParam;
import com.mindtree.vi.xml.XmlProblem;
import com.mindtree.vi.xml.XmlProblemDesc;
import com.mindtree.vi.xml.XmlProblemRequest;
import com.mindtree.vi.xml.XmlProblemResponse;

/**
 * @author m1005309
 * 
 */
public class FindSubmittedCodeServlet extends
		BaseHttpServlet<XmlProblemRequest, XmlProblemResponse> {

	@RequestParam("problemId")
	private Long problemId;

	@ReferencedBy("questionManager")
	private QuestionManager questionManager;

	@Override
	public void process() {
		XmlProblemResponse xmlResponse = new XmlProblemResponse();

		List<XmlProblem> xmlProblemList = new ArrayList<XmlProblem>();

		if (problemId != null) {
			Problem problem = questionManager.findQuestion(problemId);
			if (problem != null)
				xmlProblemList.add(constructXml(problem));
		}

		else {
			List<Problem> problemList = questionManager.findAllQuestions();
			for (Problem problem : problemList) {
				xmlProblemList.add(constructXml(problem));
			}
		}

		xmlResponse.setProblems(xmlProblemList);
		setResponse(xmlResponse);
	}

	private XmlProblem constructXml(Problem problem) {
		XmlProblem xmlProblem = new XmlProblem();
		ProblemDesc desc = problem.getProblemDescription();
		XmlProblemDesc xmlDesc = new XmlProblemDesc();
		xmlDesc.setClassName(desc.getClassName());
		xmlDesc.setMethodName(desc.getMethodName());
		xmlDesc.setParameters(desc.getMethodArguments());
		xmlDesc.setReturnType(desc.getMethodReturnType());
		xmlDesc.setProblemText(desc.getProblemText());
		xmlDesc.setProblemDescId(desc.getProblemDescId());
		xmlProblem.setProblemDescription(xmlDesc);
		xmlProblem.setProblemId(problem.getProblemId());
		return xmlProblem;
	}
}
